package com.bwie.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.bwie.pojo.Goods;
import com.bwie.pojo.req.GoodsRequest;
import com.bwie.result.PageResult;
import com.bwie.result.Result;
import com.bwie.service.EsGoodsService;
import com.bwie.utils.StringUtils;
import org.apache.http.HttpHost;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Map;

@Service
public class EsGoodsServiceImpl implements EsGoodsService {


    RestHighLevelClient client=new RestHighLevelClient(
            RestClient.builder(new HttpHost("47.102.97.160",9200,"http"))
    );

    private static final String INDEX_NAME="goods";

    @Override
    public Result<PageResult<Goods>> list(GoodsRequest goodsRequest) {
        long total=0;
        ArrayList<Goods> list = new ArrayList<>();
        try {
            SearchRequest searchRequest = new SearchRequest(INDEX_NAME);
            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
            BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
            if (StringUtils.isNotEmpty(goodsRequest.getSearchAll())){
                boolQueryBuilder.should(QueryBuilders.matchQuery("goodsName",goodsRequest.getSearchAll()));
                boolQueryBuilder.should(QueryBuilders.matchQuery("descp",goodsRequest.getSearchAll()));
                boolQueryBuilder.should(QueryBuilders.matchQuery("goodsType",goodsRequest.getSearchAll()));
                boolQueryBuilder.should(QueryBuilders.matchQuery("brand",goodsRequest.getSearchAll()));
            }
            searchSourceBuilder.query(boolQueryBuilder);
            //分页
            searchSourceBuilder.from((goodsRequest.getPageNum()-1)*goodsRequest.getPageSize());
            searchSourceBuilder.size(goodsRequest.getPageSize());
            //设置高亮
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            highlightBuilder.field("goodsName");
            highlightBuilder.preTags("<span style=\"color:red;\">");
            highlightBuilder.postTags("</span>");

            searchSourceBuilder.highlighter(highlightBuilder);
            searchRequest.source(searchSourceBuilder);

            SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
            SearchHits responseHits = searchResponse.getHits();
            total = responseHits.getTotalHits().value;
            SearchHit[] hits = responseHits.getHits();
            for (SearchHit hit : hits) {
                String sourceAsString = hit.getSourceAsString();
                Goods goods = JSONObject.parseObject(sourceAsString, Goods.class);
                goods.setId(Integer.parseInt(hit.getId()));
                Map<String, HighlightField> highlightFields = hit.getHighlightFields();
                if (highlightFields!=null){
                    HighlightField highlightField = highlightFields.get("goodsName");
                    if (highlightField!=null){
                        Text[] fragments = highlightField.fragments();
                        String str="";
                        for (Text fragment : fragments) {
                            str+=fragment;
                        }
                        goods.setGoodsName(str);
                    }
                }
                list.add(goods);
            }
            return PageResult.toResult(total,list);
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
}
